// @ts-check
import React, { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import cs from 'classnames'
import styles from './style.less'
import {
  changePlayState,
  setMusicId,
  usePlayerStateSelector, usePlayerStoreDispatch,
} from '@/components/Player/store'
import PlayerEvent from '@/components/Player/events'
import ScorllView from '../scorllView'
import { parseTime, textOverflow } from '../../utils'
import { CaretRightOutlined, PauseOutlined } from '@ant-design/icons'
import { PlayState } from '../../enums'

/** @type {React.FC<import('./type').PlaylistProps>} */
const Playlist = memo(({
  containerClassName = '',
  itemClassName = '',
  itemContainerClassName = '',
  indicatorClassName = '',
  playingTextColor = '',
  renderToolBar = () => null,
  onCurrentMusicChange = () => {}
}) => {
  const dispatch = usePlayerStoreDispatch()
  const playList = usePlayerStateSelector((state) => state.playList)
  const musicId = usePlayerStateSelector((state) => state.musicId)
  const playState = usePlayerStateSelector((state) => state.playState)
  const audioInstance = usePlayerStateSelector((state) => state.audioInstance)

  // 自动播放
  const onPlayerPrepared = useCallback(() => {
    if(audioInstance) {
      audioInstance.play()
    }
  }, [audioInstance])

  // 自动下一曲或者其他逻辑（现在只有循环播放）
  const onPlayerEnd = useCallback(() => {
    const playListLen = playList.length
    if(playListLen) {
      const findIndex = playList.findIndex(i => i.id == musicId)
      if(findIndex >= 0) {
        const nextIndex = findIndex + 1 > playListLen - 1 ? 0 : findIndex + 1
        dispatch(setMusicId(playList[nextIndex].id))
      }
    }
  }, [playList, musicId])

  const onPlayerNext = useCallback(() => {
    const playListLen = playList.length
    if(playListLen) {
      const findIndex = playList.findIndex(i => i.id == musicId)
      if(findIndex >= 0) {
        const nextIndex = findIndex + 1 > playListLen - 1 ? 0 : findIndex + 1
        dispatch(setMusicId(playList[nextIndex].id))
      }
    }
  }, [playList, musicId])
  const onPlayerPrev = useCallback(() => {
    const playListLen = playList.length
    if(playListLen) {
      const findIndex = playList.findIndex(i => i.id == musicId)
      if(findIndex >= 0) {
        const nextIndex = findIndex - 1 >= 0 ? findIndex - 1 : playListLen - 1
        dispatch(setMusicId(playList[nextIndex].id))
      }
    }
  }, [playList, musicId])
  // 注册事件
  // 事件一定要清除
  useEffect(() => {
    PlayerEvent.addListener('next', onPlayerNext)
    PlayerEvent.addListener('prev', onPlayerPrev)
    PlayerEvent.addListener('prepared', onPlayerPrepared)
    PlayerEvent.addListener('end', onPlayerEnd)

    return () => {
      // removeAllListener 不传参数清除全部事件
      // 组件销毁一般都要全部清除
      PlayerEvent.removeListener()
    }
  }, [musicId, playList])

  const onItemClick = useCallback((id) => {
    if(!audioInstance) return
    
    if(id != musicId) {
      dispatch(setMusicId(id))
    }else {
      const newState = playState == PlayState.play ? PlayState.pause : PlayState.play
      if(playState == PlayState.play) {
        audioInstance.pause()
      }else {
        audioInstance.play()
      }
      dispatch(changePlayState(newState))
    }
  }, [playState, musicId, audioInstance])

  // // 确定当前播放歌曲
  // useEffect(() => {
  //   const find = playList.find(i => i.id == musicId)
  //   if(find) {
  //     // onCurrentMusicChange && onCurrentMusicChange({music: musicId, ele: document.querySelector(`#playlist-item-${musicId}`)})
  //     /** @type {HTMLDivElement} */
  //     const ele = document.querySelector(`#playlist-item-${musicId}`)
  //     console.dir(ele.offsetTop)
  //   }
  // }, [musicId])
  return (
    <ScorllView 
      className = { cs(styles['playlistContainer'], containerClassName) }
      renderTopContent = { renderToolBar } >
      {
        playList.map(music => 
          <div 
            id = {`playlist-item-${music.id}`}
            onDoubleClick = {onItemClick.bind(null, music.id)}
            className = {cs(styles['playlistItemContainer'], itemContainerClassName)}
            style = {{color: musicId == music.id  ?  playingTextColor : undefined }}
            key = { music.id } >
            <div className = {cs(styles['playlistItem'], itemClassName)}>
              <div className = {cs(styles['indicator'], indicatorClassName)}>
                {
                  musicId == music.id  ? playState == PlayState.play ? <CaretRightOutlined/> : <PauseOutlined /> : null
                }
              </div>
              <div className={styles['name']} title = {music.name} >{ music.name }</div>
              <div className={styles['singer']} title = {music.artist}>{ music.artist }</div>
              <div className={styles['duration']}>{ parseTime(music.duration / 1000) }</div>
            </div>
          </div>)
        
      }
    </ScorllView>
  )
})

export default Playlist
